package net.csdn.business.kanban.common.filter;


import net.csdn.business.kanban.common.constant.CommonConstants;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Enumeration;

public class CorsFilter implements Filter {
    private final ICorsConfig corsConfig;

    public CorsFilter(ICorsConfig corsConfig) {
        this.corsConfig = corsConfig;
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        String origin = httpServletRequest.getHeader("Origin");
        if (StringUtils.isNotBlank(origin) && checkOrigin(origin)) {
            HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
            Enumeration<String> headers = httpServletRequest.getHeaderNames();
            StringBuilder headersStr = new StringBuilder();
            headersStr.append(corsConfig.getAccessControlAllowHeaders());
            while (headers.hasMoreElements()) {
                headersStr.append(headers.nextElement()).append(CommonConstants.COMMA);
            }
            String corsAllowHeaders = headersStr.substring(0, headersStr.length() - 1);

            httpServletResponse.setHeader("Access-Control-Allow-Origin", origin);
            httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
            httpServletResponse.setHeader("Access-Control-Allow-Headers", corsAllowHeaders);
            httpServletResponse.setHeader("Access-Control-Max-Age", "86400");
            httpServletResponse.setHeader("Access-Control-Allow-Credentials", "true");
            if (HttpMethod.OPTIONS.toString().equalsIgnoreCase(httpServletRequest.getMethod())) {
                httpServletResponse.setStatus(HttpStatus.OK.value());
                return;
            }
        }
        filterChain.doFilter(servletRequest, servletResponse);
    }

    private boolean checkOrigin(String origin) {
        // if (StringUtils.isBlank(origin)) {
        //     return false;
        // }
        for (String allowOrigin : corsConfig.getAllowOrigins()) {
            if (origin.endsWith(allowOrigin)) {
                return true;
            }
        }
        return false;
    }
}